// composables/useCursorTracker.js
import { ref } from 'vue'

const activeInput = ref(null)
const cursorPosition = ref({ start: 0, end: 0 })

export function useCursorTracker() {
  const setActiveInput = (inputElement) => {
    activeInput.value = inputElement
    if (inputElement) {
      cursorPosition.value = {
        start: inputElement.selectionStart || 0,
        end: inputElement.selectionEnd || 0
      }
    }
  }

  const updateCursorPosition = () => {
    if (activeInput.value) {
      cursorPosition.value = {
        start: activeInput.value.selectionStart || 0,
        end: activeInput.value.selectionEnd || 0
      }
    }
  }

  const insertAtCursor = (text) => {
    if (!activeInput.value) return

    const input = activeInput.value
    const startPos = cursorPosition.value.start
    const endPos = cursorPosition.value.end
    const currentValue = input.value || ''
    
    const beforeText = currentValue.substring(0, startPos)
    const afterText = currentValue.substring(endPos, currentValue.length)
    const newValue = beforeText + text + afterText
    
    // 更新输入框的值
    input.value = newValue
    
    // 触发input事件，使Vue能够捕获到值的变化
    const event = new Event('input', { bubbles: true })
    input.dispatchEvent(event)
    
    // 设置光标位置到插入字符之后
    setTimeout(() => {
      const newCursorPos = startPos + text.length
      input.selectionStart = input.selectionEnd = newCursorPos
      input.focus()
    }, 0)
  }

  return {
    activeInput,
    cursorPosition,
    setActiveInput,
    updateCursorPosition,
    insertAtCursor
  }
}